const express = require("express");
const router = express.Router();
const path = require("path");
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const utilsServer = require("../utils/serverInfo.js");
const moment = require("moment-timezone");
const multer = require("multer");
const AdmZip = require("adm-zip");
const AppInfoParser = require("app-info-parser");
const plist = require("plist");
const fs = require("fs");
const { readManifest } = require("node-aab-parser");
const msgUtils = require("../utils/feishu.js");
const crypto = require("crypto");
const CryptoJS = require("crypto-js");
const FormData = require("form-data");
const { exec } = require("child_process");
const config = require("../config");
const axios = require("axios");
const jwt = require("jsonwebtoken");
const jwksClient = require('jwks-rsa');


router.get('/getWaListjs', (req, res) => {
    // 构造文件路径
    const filePath = path.join('/wajs', `list.zip`);
    // 检查文件是否存在
    fs.access(filePath, fs.constants.R_OK, (err) => {
        if (err) {
            return res.status(404).send("文件未找到。");
        }

        // 设置下载响应头
        res.setHeader('Content-Disposition', `attachment; filename="list.zip"`);
        res.setHeader('Content-Type', 'application/zip');

        // 使用文件流发送文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res);
    });
});
router.get('/getWaChatjs', (req, res) => {
    // 构造文件路径
    const filePath = path.join('/wajs', `chat.zip`);
    // 检查文件是否存在
    fs.access(filePath, fs.constants.R_OK, (err) => {
        if (err) {
            return res.status(404).send("文件未找到。");
        }

        // 设置下载响应头
        res.setHeader('Content-Disposition', `attachment; filename="chat.zip"`);
        res.setHeader('Content-Type', 'application/zip');

        // 使用文件流发送文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res);
    });
});
router.get('/getWaIncognitojs', (req, res) => {
    // 构造文件路径
    const filePath = path.join('/wajs', `incognito.zip`);
    // 检查文件是否存在
    fs.access(filePath, fs.constants.R_OK, (err) => {
        if (err) {
            return res.status(404).send("文件未找到。");
        }

        // 设置下载响应头
        res.setHeader('Content-Disposition', `attachment; filename="incognito.zip"`);
        res.setHeader('Content-Type', 'application/zip');

        // 使用文件流发送文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res);
    });
});
router.get('/getFileUpdateStatus', async (req, res) => {
    let sql = `SELECT * FROM js_app_file_update_status LIMIT 1`
    let result = await mysqlQuery(sql, [])
    res.send(utils.returnData({ data: result }));
})
router.post('/report', async (req, res) => {

    const { type, uuid, ios_version, lang, device, region } = req.body
    let content = {}
    content.id = utils.createId();
    content.type = type;
    content.region = region;
    content.ios_version = ios_version;
    content.uuid = uuid;
    content.lang = lang;
    content.device = device;
    content.eventTimeMillis = Date.now();

    content.create_date = utils.formatDate(new Date());
    content.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql("wa_event_tracking", content);
    let result = await utils.query(text, values);
    res.send({
        code: 0,
        msg: "success",
    });
})
router.post('/reportDailyAppOpenCount', async (req, res) => {
    const { uuid, startType } = req.body;

    const numericStartType = Number(startType);
    if (!uuid || isNaN(numericStartType) || ![1, 2].includes(numericStartType)) {
        return res.send({ code: 400, msg: "参数错误" });
    }
    try {
        // 获取当前日期（格式：YYYY-MM-DD）
        const currentDate = moment().format('YYYY-MM-DD'); // 需要安装moment.js
        // 或使用纯JS：
        // const currentDate = new Date().toISOString().split('T')[0];

        // 根据启动类型设置初始值
        let coldStart = numericStartType == 1 ? 1 : 0;
        let warmStart = numericStartType == 2 ? 1 : 0;

        /**
         * 使用 ON DUPLICATE KEY UPDATE 实现：
         * 1. 需要确保数据库表有唯一索引 UNIQUE(uuid, date)
         * 2. 如果记录存在则执行次数累加
         * 3. 不存在则插入新记录
         */
        const sql = `
            INSERT INTO wa_daily_app_open_stats 
                (id,uuid, date, cold_start, warm_start,create_date,update_date)
            VALUES (?,?,?,?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                cold_start = cold_start + VALUES(cold_start),
                warm_start = warm_start + VALUES(warm_start)
        `;

        // 执行SQL（参数按顺序对应占位符）
        await mysqlQuery(sql, [utils.createId(), uuid, currentDate, coldStart, warmStart, utils.formatDate(new Date()), utils.formatDate(new Date())]);
        //----------------------------------------------------------------------
        // 2. 再插一条明细到 wa_app_open_log
        //----------------------------------------------------------------------
        const sqlAppOpenLog = `
        INSERT INTO wa_app_open_log
                   (id, uuid, cold_start, warm_start, event_timestamp, create_date, update_date)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
        await mysqlQuery(sqlAppOpenLog, [
            utils.createId(),
            uuid,
            coldStart,
            warmStart,
            Date.now(),                          // 存毫秒级时间戳
            utils.formatDate(new Date()),
            utils.formatDate(new Date())
        ]);
        res.send({
            code: 0,
            msg: "success",
        });
    } catch (error) {
        console.error('统计失败:', error);
        res.status(500).send({
            code: 500,
            msg: "服务器内部错误",
        });
    }
});

//每天人均进入app次数
router.post('/daily_avg_app_entry_per_user', async (req, res) => {
    const { dateRange } = req.body;
    let sql = `SELECT * FROM wa_daily_app_open_summary`;
    let params = [];
    if (dateRange && dateRange.start && dateRange.end) {
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` where date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }
    try {
        const results = await mysqlQuery(sql, params);
        results.forEach(row => {
            row.date = moment(row.date).format('MM-DD') // 提取并格式化日期
        });
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }

});


// 查询每日刷新率数据接口
router.post('/daily_summary', async (req, res) => {
    // 从请求体中获取日期区间条件，格式如：{ start: '2025-02-15', end: '2025-02-18' }
    const { dateRange } = req.body;

    // 初始SQL语句，从每日数据汇总表中查询所有数据
    let sql = `SELECT * FROM wa_event_daily_summary`;
    let params = [];

    // 如果传递了日期区间，则拼接查询条件
    if (dateRange && dateRange.start && dateRange.end) {
        // 日期字段在新表中为 summary_date，确保查询条件是日期格式 (YYYY-MM-DD)
        const startDate = moment(dateRange.start).format('YYYY-MM-DD');
        const endDate = moment(dateRange.end).format('YYYY-MM-DD');
        sql += ` WHERE summary_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    try {
        // 执行SQL查询，获取每日汇总数据
        const results = await mysqlQuery(sql, params);

        // 将返回的日期格式化，如：将 summary_date 格式化为 MM-DD 形式
        results.forEach(row => {
            row.summary_date = moment(row.summary_date).format('MM-DD');
        });

        // 返回查询结果
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        console.error('查询每日统计数据失败：', error);
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }
});


// 查询每两小时刷新率数据接口（用于 Echarts 展示）
// 该接口自动计算当前时间往前两天的日期区间，无需前端传入日期条件
router.post('/wa_event_statistics', async (req, res) => {
    try {
        // 计算查询日期区间
        // endDate 为当前日期（YYYY-MM-DD 格式），startDate 为两天前的日期
        const endDate = moment().format('YYYY-MM-DD');
        const startDate = moment().subtract(2, 'days').format('YYYY-MM-DD');

        // 构造 SQL 查询语句，按照 create_date 字段进行区间过滤，并按日期排序（可根据业务需要调整排序字段）
        const sql = `
            SELECT *
            FROM wa_event_statistics
            WHERE create_date BETWEEN ? AND ?
            ORDER BY create_date ASC
        `;
        const params = [startDate, endDate];

        // 执行 SQL 查询，查询最近两天的数据
        const results = await mysqlQuery(sql, params);
        results.forEach(row => {
            row.start_time = moment(row.start_time).format('HH:00');
        });
        // 直接返回查询结果，前端可根据需求对数据加工后在 Echarts 中展示
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        console.error('查询每两小时刷新率数据失败：', error);
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }
});


//测试卡片
//测试卡片
router.post('/cardTest', async (req, res) => {
    let token = await msgUtils.getTenantAccessToken();
    let msg_type = "interactive";
    let id = `oc_300d536417e7a4d6a47c27bc43b00bb0`;

    let iosData = [
        { ios_version: '15.8', count: 1 },
        { ios_version: '15.8.2', count: 1 },
        { ios_version: '15.8.3', count: 2 },
        { ios_version: '16.2', count: 1 },
        { ios_version: '16.7.10', count: 2 },
        { ios_version: '17.3.1', count: 10 },
        { ios_version: '17.5.1', count: 3 },
        { ios_version: '18.0', count: 2 },
        { ios_version: '18.0.1', count: 1 },
        { ios_version: '18.1.1', count: 2 },
        { ios_version: '18.2', count: 2 },
        { ios_version: '18.2.1', count: 1 }
    ];
    // 按 count 从高到低排序
    iosData.sort((a, b) => b.count - a.count);

    // 如果数据数量超过10个，只保留前10个
    const maxItems = 10;
    const filteredData = iosData.slice(0, maxItems);

    let content = ` 当前设定预警阈值:0.1\n 警报触发于:02:00\n 刷新率变化:2.1%\n 当前时段进入web人次:1333,刷新人次:14,刷新率:0.2%\n 前次时段进入web人次:2999,刷新人次:23,刷新率:2%`
    let at = `<at id="g1eff8g3">(产品)</at><at id="8d333cd2"></at><at id="5bfbfa32">(测试)</at><at id="c47a29d7">(测试)</at>`
    // 查询最近6条刷新率记录（按创建时间降序排序）
    const recentRefreshQuery = `
  SELECT *,
         DATE_FORMAT(create_date, '%m-%d %H:%i') AS formatted_create_date
  FROM wa_event_statistics
  ORDER BY create_date DESC
  LIMIT 12
`;

    let recentRefreshRows = await utils.query(recentRefreshQuery);
    // 保证在折线图中数据按时间从早到晚排列
    recentRefreshRows.reverse();
    const pad = (n) => n.toString().padStart(2, '0');
    const lineData = recentRefreshRows.map(row => {
        const start = new Date(row.start_time);
        const end = new Date(row.end_time);
        const timeRange = `${pad(start.getHours())}-${pad(end.getHours())}`;
        return {
            time: timeRange,
            current_refresh_rate: row.current_refresh_rate,
            web_count: row.web_count,
            reflash_count: row.reflash_count,
            mode_count: row.mode_count,
            tooltipText: `时间: ${timeRange}\n进入web人次: ${row.web_count}\n刷新次数: ${row.reflash_count}\nmode次数: ${row.mode_count}`
        };
    });
    // console.log(lineData)
    // return
    // 模拟一组折线图数据


    let contentMsg = {
        config: { wide_screen_mode: true, update_multi: true },
        i18n_elements: {
            zh_cn: [
                {
                    tag: "markdown",
                    content: `${at}`,
                    text_align: "left",
                    text_size: "normal"
                },
                {
                    tag: "hr"
                },
                {
                    tag: "markdown",
                    content: `${content}`,
                    text_align: "left",
                    text_size: "normal"
                },
                {
                    tag: "hr"
                },
                {
                    tag: "chart",
                    chart_spec: {
                        type: "bar",
                        title: { text: "刷新类型的iOS版本分布" },
                        data: {
                            values: filteredData.map((item) => ({
                                type: "iOS",
                                ios_version: item.ios_version,
                                count: item.count
                            }))
                        },
                        xField: ["ios_version", "type"],
                        yField: "count",
                        seriesField: "type",
                        legends: { visible: false, orient: "bottom" }
                    },
                    preview: true,
                    color_theme: "brand",
                    height: "auto"
                },
                // 新增的折线图
                {
                    tag: "chart",
                    chart_spec: {
                        type: "line",
                        title: { text: "刷新趋势折线图" },
                        data: {
                            values: lineData
                        },
                        xField: "time",
                        yField: "current_refresh_rate",
                        // 此处不再配置 tooltip
                        legends: { visible: false }
                    },
                    preview: true,
                    color_theme: "brand",
                    height: "auto"
                },

                // 将取出的完整数据以 tips 展示（可选）

                {
                    tag: "person_list",
                    persons: [
                        {
                            "id": "g1eff8g3"
                        },
                        {
                            "id": "8d333cd2"
                        },
                        {
                            "id": "5bfbfa32"
                        },
                        {
                            "id": "c47a29d7"
                        }
                    ],
                    size: "small",
                    show_avatar: true,
                    show_name: false
                }
            ]
        },
        i18n_header: {
            zh_cn: {
                title: {
                    tag: "plain_text",
                    content: "🚨 警报！web 可能不稳定，刷新有突发增长的情况"
                },
                template: "red"
            }
        }
    };
    let jsonString = JSON.stringify(contentMsg);
    await msgUtils.sendMessage(id, msg_type, jsonString, token);
});

//查询2小时段刷新率列表
router.post('/reportSummary', async (req, res) => {
    const { dateRange } = req.body;
    let sql = `
        SELECT *,
       DATE_FORMAT(start_time, '%m-%d %H:%i') AS formatted_start_time,
       DATE_FORMAT(end_time, '%H:%i') AS formatted_end_time
FROM wa_event_statistics
    `;
    const params = [];

    if (dateRange && dateRange.start && dateRange.end) {
        // Format the start and end dates to include full day range
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` WHERE create_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    try {
        // Execute the query with the prepared parameters
        const rows = await utils.query(sql, params);

        // Format the query results to add the time range information
        const formattedRows = rows.map(row => {
            return {
                ...row,
                time_range: `${row.formatted_start_time}-${row.formatted_end_time}`,
            };
        });

        // Return the results using util's returnData method
        res.send(utils.returnData({
            data: formattedRows
        }));
    } catch (error) {
        console.error('Error querying aggregated stats:', error);
        res.status(500).send({
            code: 1,
            msg: "An error occurred while querying the report summary",
        });
    }
});



//查询进入web的日活数据
router.post('/queryWebDailyActiveUsers', async (req, res) => {
    const { dateRange } = req.body;
    let sql = `SELECT * FROM wa_event_daily_summary`;
    let params = [];
    if (dateRange && dateRange.start && dateRange.end) {
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` where summary_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }
    try {
        const results = await mysqlQuery(sql, params);
        results.forEach(row => {
            row.date = moment(row.summary_date).format('MM-DD') // 提取并格式化日期
        });
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }
})
//查询进入APP的日活数据
router.post('/queryAppDailyActiveUsers', async (req, res) => {
    const { dateRange } = req.body;
    let sql = `SELECT * FROM wa_daily_app_open_summary`;
    let params = [];
    if (dateRange && dateRange.start && dateRange.end) {
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` where date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }
    try {
        const results = await mysqlQuery(sql, params);
        results.forEach(row => {
            row.date = moment(row.date).format('MM-DD') // 提取并格式化日期
        });
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }
})

//查询时段数据
router.post('/queryAggregatedStats', async (req, res) => {
    const { dateRange } = req.body;
    let sql = `SELECT * FROM aggregated_app_open_stats`;
    const params = [];

    if (dateRange && dateRange.start && dateRange.end) {
        // 使用 hour_start 字段，按照一天的起始和结束时间进行查询
        const startDate = moment(dateRange.start)
            .startOf('day')
            .subtract(1, 'hours')
            .format('YYYY-MM-DD HH:mm:ss');

        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` WHERE hour_start BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }
    try {
        const results = await mysqlQuery(sql, params);
        // 将 hour_start 格式化为 'MM-DD HH:mm' 形式
        results.forEach(row => {
            row.hour_start = moment(row.hour_start).format('MM-DD HH:mm');
        });
        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        console.error('Error querying aggregated stats:', error);
        res.status(500).json({
            success: false,
            message: 'Internal Server Error'
        });
    }
});

router.post('/discount-probability-draw', async (req, res) => {
    try {
        // 1. 接收参数（目前只接收，不做处理）
        const { uuid, tier1_count, tier2_count, tier3_count } = req.body;

        // 2. 获取概率配置启用（status=1）的所有列表
        const sql = 'SELECT * FROM wa_discount_probability WHERE status=1';
        const list = await mysqlQuery(sql);

        // 3. 基础校验
        if (!list || list.length === 0) {
            // 没有启用的概率配置
            return res.status(404).json({ code: 404, message: '没有有效的概率配置' });
        }

        // 4. 准备"三挡"的实际概率（只用list里第一个配置；如需用全部配置，逻辑可调整为多组抽取）
        const probRow = list[0];

        // 各档的概率（number），例如 90、8、2
        const tier1_prob = Number(probRow.tier1_actual_probability); // 第一档
        const tier2_prob = Number(probRow.tier2_actual_probability); // 第二档
        const tier3_prob = Number(probRow.tier3_actual_probability); // 第三档
     
        // 概率之和（理论应为100%），如后续需求有变可动态计算
        const totalProb = tier1_prob + tier2_prob + tier3_prob;
        // console.log(totalProb,'totalProb')
        // 5. 抽取一个挡位——[1, 2, 3]
        // 产生一个[0, 100)之间的随机数，根据三档概率决定档位
        let randomVal = Math.random() * totalProb; // 0<= x < totalProb
        // console.log(tier1_prob,'tier1_prob')
        // console.log(tier2_prob,'tier2_prob')
        // console.log(tier3_prob,'tier3_prob')
        // console.log(randomVal,'randomVal')
        // console.log(randomVal, 'randomVal')

        let result_tier = 1; // 默认1档

        if (randomVal < tier1_prob) {
            result_tier = 1;
        } else if (randomVal < tier1_prob + tier2_prob) {
            result_tier = 2;
        } else {
            result_tier = 3;
        }
        console.log(result_tier)
        // 6. 返回数据，包含所有配置list，以及本次抽中档位
        res.json({
            code: 0,
            message: 'success',
            list,            // 全部配置
            result_tier      // 本次命中的挡位：1/2/3
        });

    } catch (err) {
        // 错误日志输出
        console.error('wa_discount_probability_draw接口异常', err);
        res.status(500).json({ code: 500, message: '服务器异常', err: err.toString() });
    }
});

async function mysqlQuery(sql, arr) {

    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
module.exports = router;
